﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
using DVDFilmoteka.SaveloadManagement;
using DVDFilmoteka.ServerDatabaseManagement;
using DVDFilmoteka.Settings;
using DVDFilmoteka.UpdateManagement;
using Microsoft.Win32;
using MovieStorage;
using DVDFilmoteka.Sorting;
using System.Net;
using System.Text;
using System.IO;
using DVDFilmoteka.src;
using System.Threading;
using System.Globalization;

namespace DVDFilmoteka.Forms
{
    public partial class MainForm : LocalizableForm
    {        
        private List<MovieDataStore12> filmList = new List<MovieDataStore12>();
        private Boolean transaction;
        private int pozice = -1;

        private Saver saver;
        private Loader loader;
        private Boolean saved = true;

        private Int32 filteredMovies = 0;

        public MainForm()
        {
            InitializeComponent();

            String directory = "";
            String[] cmd = Environment.GetCommandLineArgs();
            if (cmd.Length > 0 && !String.IsNullOrEmpty(cmd[0]))
            {
                int pos = cmd[0].LastIndexOf('\\');
                directory = cmd[0].Substring(0, pos);
            }
            else
            {
                RegistryKey regKeyAppRoot = Registry.LocalMachine.OpenSubKey("Software\\MJ Design\\DVD Filmoteka");
                if (regKeyAppRoot == null) return;

                directory = (string) regKeyAppRoot.GetValue("directory", "");
            }

            if (!String.IsNullOrEmpty(directory))
            {
                Environment.CurrentDirectory = directory;
            }            
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            this.Size = SettingsManager.Instance.Data.LastWindowPosition.Size;
            this.Location = SettingsManager.Instance.Data.LastWindowPosition.Location;
            
            Localize();

            comboBoxMyRating.Items.Clear();
            comboBoxMyRating.Items.AddRange(Tools.loadDataFromXML(Tools.CONFIG, "//root/mhodnoceni/*").ToArray());
            if (comboBoxMyRating.Items.Count > 0) comboBoxMyRating.SelectedIndex = 2;

            object[] list = Tools.getZanrNodeList().ToArray();
            comboBoxMainGenre.Items.Clear();
            comboBoxMainGenre.Items.AddRange(list);
            if (comboBoxMainGenre.Items.Count > 0) comboBoxMainGenre.SelectedIndex = 0;

            checkedListBoxOtherGenres.Items.AddRange(list);

            comboBoxMedia.Items.Clear();
            comboBoxMedia.Items.AddRange(Tools.loadDataFromXML(Tools.CONFIG, "//root/mmedium/*").ToArray());
            if (comboBoxMedia.Items.Count > 0) comboBoxMedia.SelectedIndex = 0;

            comboBoxQuality.Items.Clear();
            comboBoxQuality.Items.AddRange(Tools.loadDataFromXML(Tools.CONFIG, "//root/mkvalita/*").ToArray());
            if (comboBoxQuality.Items.Count > 0) comboBoxQuality.SelectedIndex = 0;

            comboBoxCompresion.Items.Clear();
            comboBoxCompresion.Items.AddRange(Tools.loadDataFromXML(Tools.CONFIG, "//root/mkomprese/*").ToArray());
            if (comboBoxCompresion.Items.Count > 0) comboBoxCompresion.SelectedIndex = 0;

            comboBoxContainer.Items.Clear();
            comboBoxContainer.Items.AddRange(Tools.loadDataFromXML(Tools.CONFIG, "//root/mkontejner/*").ToArray());
            if (comboBoxContainer.Items.Count > 0) comboBoxContainer.SelectedIndex = 0;

            comboBoxLanguage.Items.Clear();
            comboBoxLanguage.Items.AddRange(Tools.loadDataFromXML(Tools.CONFIG, "//root/mjazyk/*").ToArray());
            if (comboBoxLanguage.Items.Count > 0) comboBoxLanguage.SelectedIndex = 0;

            comboBoxChanelCount.Items.Clear();
            comboBoxChanelCount.Items.AddRange(Tools.loadDataFromXML(Tools.CONFIG, "//root/mpocetKanalu/*").ToArray());
            if (comboBoxChanelCount.Items.Count > 0) comboBoxChanelCount.SelectedIndex = 0;

            comboBoxSize.Items.Clear();
            comboBoxSize.Items.AddRange(Tools.loadDataFromXML(Tools.CONFIG, "//root/mvelikost/*").ToArray());
            if (comboBoxSize.Items.Count > 0) comboBoxSize.SelectedIndex = 0;            

            IComparer myCompIntl = new Tools.NodeSorter();
            treeView1.TreeViewNodeSorter = myCompIntl;

            ApplicationUpdater.Instance.OnVersionGet += OnVersionGetEventHandler;
            if (SettingsManager.Instance.Data.AutomaticUpdate) ApplicationUpdater.Instance.checkNewVersionAsync(false);            

            comboBoxSorting.SelectedIndex = 0;

            // Na prikazove radce je soubor k otevreni
            Boolean upgraded = false;
            String[] cmd = Environment.GetCommandLineArgs();
            if (cmd.Length > 1)
            {
                loader = new Loader();
                try
                {
                    filmList = loader.load(cmd[1], out upgraded);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message);
                    return;
                }
                
                saver = new Saver(cmd[1]);
                saved = !upgraded;
                Text = upgraded ? String.Format(Properties.Messages.form_main_text, cmd[1] + "*") : String.Format(Properties.Messages.form_main_text, cmd[1]);
                                
                updateFilmList();
            }
            else if (!String.IsNullOrEmpty(SettingsManager.Instance.Data.LastLoadedFile))
            {
                loader = new Loader();
                try
                {
                    filmList = loader.load(SettingsManager.Instance.Data.LastLoadedFile, out upgraded);
                }
                catch (Exception)
                {
                    return;
                }

                saver = new Saver(SettingsManager.Instance.Data.LastLoadedFile);
                saved = !upgraded;
                Text = upgraded ? String.Format(Properties.Messages.form_main_text, SettingsManager.Instance.Data.LastLoadedFile + "*") : String.Format(Properties.Messages.form_main_text, SettingsManager.Instance.Data.LastLoadedFile);

                updateFilmList();
            }
            else
            {
                Text = String.Format(Properties.Messages.form_main_text, Properties.Messages.messages_notsaved);
            }

            // Nastaveni jazyka
            if (String.IsNullOrEmpty(SettingsManager.Instance.Data.Language)) // Pojistka, nemelo by se stat
            {
                Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture; // Jazyk OS
                SettingsManager.Instance.Data.Language = CultureInfo.InstalledUICulture.Name;
                SettingsManager.Instance.SaveToFile();
            }
            else
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(SettingsManager.Instance.Data.Language); // Vybrany jazyk
            }            
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            handleUnsaved();

            Rectangle rect = new Rectangle(this.Location, this.Size);

            SettingsManager.Instance.Data.LastWindowPosition = rect;
            if (saver != null) SettingsManager.Instance.Data.LastLoadedFile = saver.FileName;

            SettingsManager.Instance.SaveToFile();
        }

        #region update treeview
        private void updateFilmList()
        {
            MovieDataStore12 selectedNode = null;
            if (treeView1.SelectedNode != null && (treeView1.SelectedNode.Tag is MovieDataStore12)) selectedNode = (MovieDataStore12)treeView1.SelectedNode.Tag;
            
            // Zacit upravovat
            treeView1.BeginUpdate();
            transaction = true;

            // Aplikuje filtr
            if (!String.IsNullOrEmpty(textBoxFilter.Text))
            {
                List<MovieDataStore12> filteredMovieList = new List<MovieDataStore12>();
                foreach (var item in filmList)
                {
                    String name = item.czechName;
                    if (SorterStrategy.getSorter().Category() == ESorters.ABECEDNI_ORIGINAL)
                    {
                        name = item.originalName;
                    }

                    if (name != null && name.ToLower().Contains(textBoxFilter.Text.ToLower()))
                    {
                        filteredMovieList.Add(item);
                    }
                }

                // Naplni treeview filmy
                SorterStrategy.getSorter().Sort(treeView1, filteredMovieList);
                filteredMovies = filteredMovieList.Count;
            } else {
                // Naplni treeview filmy
                SorterStrategy.getSorter().Sort(treeView1, filmList);
                filteredMovies = filmList.Count;
            }

            // Setridi
            treeView1.Sort();

            transaction = false;
            
            // Najde predtim vybrany Node
            treeView1.SelectedNode = null;
            foreach (TreeNode item in treeView1.Nodes)
            {
                if (item.Nodes != null && item.Nodes.Count > 0) // 2 a vice pater
                {
                    foreach (TreeNode item2 in item.Nodes)
                    {
                        if (item2.Nodes != null && item2.Nodes.Count > 0) // 3 patra
                        {
                            foreach (TreeNode item3 in item2.Nodes)
                            {
                                MovieDataStore12 filmData = (MovieDataStore12)item3.Tag;
                                if (selectedNode != null && filmData.Equals(selectedNode))
                                {
                                    treeView1.SelectedNode = item3;
                                    break;
                                }
                            }
                            if (treeView1.SelectedNode != null) break;
                        }
                        else // 2 patra
                        {
                            MovieDataStore12 filmData = (MovieDataStore12)item2.Tag;
                            if (selectedNode != null && filmData.Equals(selectedNode))
                            {
                                treeView1.SelectedNode = item2;
                                break;
                            }
                        }
                    }
                    if (treeView1.SelectedNode != null) break;
                }
                else // 1 patro
                {
                    MovieDataStore12 filmData = (MovieDataStore12)item.Tag;
                    if (selectedNode != null && filmData.Equals(selectedNode))
                    {
                        treeView1.SelectedNode = item;
                        break;
                    }
                }
            }
            treeView1_AfterSelect(null, null);
            treeView1.EndUpdate();

            updateMovieCountVisual();
        }
        
        #endregion

        #region import
        
        public void addFilmDataStore(List<MovieDataStore12> _filmList)
        {
            if (_filmList.Count <= 0) return;

            filmList.AddRange(_filmList);            
            saved = false;
            if (saver != null)
            {
                Text = String.Format(Properties.Messages.form_main_text, saver.FileName + "*");
            }

            updateFilmList();
        }
        #endregion

        #region Zmeny datovych policek

        /// <summary>
        /// Kliknuto na herce
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBoxActors_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBoxActors.SelectedItem != null && treeView1.SelectedNode != null && treeView1.SelectedNode.Tag != null && (treeView1.SelectedNode.Tag is MovieDataStore12))
            {
                String link = "";
                try
                {
                    link = (treeView1.SelectedNode.Tag as MovieDataStore12).actors[(String)listBoxActors.SelectedItem];
                }
                catch { }

                if (!String.IsNullOrEmpty(link)) Tools.openPageInBrowser(link);
            }
        }
        
        /// <summary>
        /// Zmena specifikace trizeni
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxSorting_SelectedIndexChanged(object sender, EventArgs e)
        {
            SorterStrategy.getSorter().SaveExpanded(treeView1);

            Tools.SorterItem item = comboBoxSorting.SelectedItem as Tools.SorterItem;
            if (item != null)
            {
                SorterStrategy.setSorter(item.Sorter);
                updateFilmList();
            }
        }

        /// <summary>
        /// Zmena ceskeho jmena
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxCzechName_TextChanged(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null) return; // Kdyz neni oznaceny zadny node

            if (SorterStrategy.getSorter().Category() == ESorters.ABECEDNI_CESKY)
            {
                if (String.IsNullOrEmpty(textBoxCzechName.Text) || treeView1.SelectedNode.Text[0] != textBoxCzechName.Text[0])
                {
                    somethingChanged(sender, e);
                    return;
                }
            }

            if (!transaction)
            {
                treeView1.SelectedNode.Text = textBoxCzechName.Text;

                if (!(treeView1.SelectedNode.Tag is MovieDataStore12)) return;
                MovieDataStore12 filmData = (MovieDataStore12) treeView1.SelectedNode.Tag;
                if (filmData == null) return;

                filmData.czechName = textBoxCzechName.Text;

                saved = false;
                if (saver != null)
                {
                    Text = String.Format(Properties.Messages.form_main_text, saver.FileName + "*");
                }
            }
        }

        /// <summary>
        /// Zmena originalniho jmena
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxOriginalName_TextChanged(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null) return; // Kdyz neni oznaceny zadny node

            Boolean a = SorterStrategy.getSorter().Category() == ESorters.ZANR;

            if (!a || String.IsNullOrEmpty(textBoxOriginalName.Text) || treeView1.SelectedNode.Text[0] != textBoxOriginalName.Text[0])
            {
                somethingChanged(sender, e);
                return;
            }

            if (!transaction)
            {
                treeView1.SelectedNode.Text = textBoxOriginalName.Text;

                if (!(treeView1.SelectedNode.Tag is MovieDataStore12)) return;
                MovieDataStore12 filmData = (MovieDataStore12) treeView1.SelectedNode.Tag;
                if (filmData == null) return;

                filmData.originalName = textBoxOriginalName.Text;

                saved = false;
                if (saver != null)
                {
                    Text = String.Format(Properties.Messages.form_main_text, saver.FileName + "*");
                }
            }
        }

        /// <summary>
        /// Zmena zanru
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkedListBoxOtherGenres_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<GenreItem> zanrList = Tools.getZanrNodeList();            

            transaction = true;

            GenreItem mainGenre = (comboBoxMainGenre.SelectedItem as GenreItem);
            
            comboBoxMainGenre.Items.Clear();
            foreach (GenreItem item in checkedListBoxOtherGenres.CheckedItems) //Naplnit kombobox vybranymi zanry
            {
                comboBoxMainGenre.Items.Add(item);
            }

            if (comboBoxMainGenre.Items.Count <= 0) comboBoxMainGenre.Items.Add(Tools.NoGenre);
            comboBoxMainGenre.SelectedIndex = comboBoxMainGenre.Items.IndexOf(mainGenre) >= 0 ? comboBoxMainGenre.Items.IndexOf(mainGenre) : 0;

            transaction = false;

            somethingChanged(sender, e);
        }

        /// <summary>
        /// Zmena zanru
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkedListBoxOtherGenres_KeyPress(object sender, KeyPressEventArgs e)
        {
            checkedListBoxOtherGenres_SelectedIndexChanged(sender, null);
        }

        /// <summary>
        /// Zmena jakehokoliv datoveho policka
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void somethingChanged(object sender, EventArgs e)
        {
            handleMediaTypeChanged();

            if (treeView1.SelectedNode == null || treeView1.SelectedNode.Tag == null || !(treeView1.SelectedNode.Tag is MovieDataStore12)) return;
                        
            if (!transaction)
            {
                MovieDataStore12 filmData = (MovieDataStore12)treeView1.SelectedNode.Tag;
                if (filmData == null) return;

                Boolean update = false;
                if (!filmData.czechName.Equals(textBoxCzechName.Text) && (SorterStrategy.getSorter().Category() == ESorters.ABECEDNI_CESKY || SorterStrategy.getSorter().Category() == ESorters.ZADNY)) update = true;
                if (!filmData.originalName.Equals(textBoxOriginalName.Text) && SorterStrategy.getSorter().Category() == ESorters.ABECEDNI_ORIGINAL) update = true;
                if (!filmData.mainGenre.Equals((comboBoxMainGenre.SelectedItem as GenreItem).Name) && SorterStrategy.getSorter().Category() == ESorters.ZANR) update = true;
                if (!filmData.compression.Equals((String)comboBoxCompresion.SelectedItem) && SorterStrategy.getSorter().Category() == ESorters.KOMPRESE) update = true;

                filmData.czechName = textBoxCzechName.Text;
                filmData.originalName = textBoxOriginalName.Text;
                filmData.link = textBoxLinks.Text;
                filmData.movieNotes = textBoxMovieNotes.Text;
                filmData.resolution = textBoxResolution.Text;
                filmData.mediumNotes = textBoxMediaNotes.Text;                

                filmData.myRating = (String)comboBoxMyRating.SelectedItem;
                filmData.mainGenre = (comboBoxMainGenre.SelectedItem as GenreItem).Name;
                filmData.medium = (String)comboBoxMedia.SelectedItem;
                filmData.quality = (String)comboBoxQuality.SelectedItem;
                filmData.compression = (String)comboBoxCompresion.SelectedItem;
                filmData.container = (String)comboBoxContainer.SelectedItem;
                filmData.size = (String)comboBoxSize.SelectedItem;
                filmData.language = (String)comboBoxLanguage.SelectedItem;
                filmData.channelCount = (String)comboBoxChanelCount.SelectedItem;

                filmData.otherGenre.Clear();
                foreach (GenreItem item in checkedListBoxOtherGenres.CheckedItems)
                {
                    filmData.otherGenre.Add(item.ID);
                }

                if (update) updateFilmList();
                
                saved = false;
                if (saver != null)
                {
                    Text = String.Format(Properties.Messages.form_main_text, saver.FileName + "*");
                }
            }
        }

        /// <summary>
        /// Nastaveni obrazku filmu
        /// </summary>
        private void moviePictureChanged(String link)
        {
            if (treeView1.SelectedNode == null || treeView1.SelectedNode.Tag == null || !(treeView1.SelectedNode.Tag is MovieDataStore12)) return;

            MovieDataStore12 filmData = (MovieDataStore12)treeView1.SelectedNode.Tag;
            if (filmData == null) return;

            if (!String.IsNullOrEmpty(link))
            {
                filmData.pictureLink = link;
                pictureBoxMoviePicture.Image = Properties.Resources.loading;

                if (!SettingsManager.Instance.Data.LoadPicturesOnline)
                {
                    WebClient client = new WebClient();
                    if (!SettingsManager.Instance.Data.UseDefaultProxy)
                    {
                        WebProxy proxy = new WebProxy(SettingsManager.Instance.Data.ProxyIPAddress.ToString(),
                                                      SettingsManager.Instance.Data.ProxyPort);
                        client.Proxy = proxy;
                    }
                    else
                    {
                        client.Proxy = WebRequest.GetSystemWebProxy();
                    }

                    byte[] data = client.DownloadData(link); // Nacist obrazek z netu
                    if (data != null)
                    {
                        filmData.pictureData = Convert.ToBase64String(data); // Ulozit v Base64
                        
                        MemoryStream imageStream = new MemoryStream(data);
                        imageStream.Position = 0;

                        pictureBoxMoviePicture.Image = new Bitmap(imageStream); // Zobrazit
                    }
                    else
                    {                            
                        filmData.pictureData = "";
                        pictureBoxMoviePicture.Image = pictureBoxMoviePicture.ErrorImage;
                    }                    
                }
                else
                {
                    filmData.pictureData = "";
                    try
                    {
                        pictureBoxMoviePicture.Load(link); // Zobrazit on-line
                    } catch {
                        pictureBoxMoviePicture.Image = pictureBoxMoviePicture.ErrorImage;
                    }
                }
            }            
        }

        private void somethingChanged(object sender, KeyPressEventArgs e)
        {
            somethingChanged(sender, null);
        }

        /// <summary>
        /// Zmena policka filtru
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxFilter_TextChanged(object sender, EventArgs e)
        {
            updateFilmList();
        }

        /// <summary>
        /// Zmena typu media
        /// </summary>
        private void handleMediaTypeChanged()
        {
            if (comboBoxMedia.SelectedIndex < 0 || comboBoxQuality.SelectedIndex < 0) return;

            // Vybrano DVD
            if ("DVD".Equals(comboBoxMedia.Items[comboBoxMedia.SelectedIndex]) && "DVD-Video".Equals(comboBoxQuality.Items[comboBoxQuality.SelectedIndex]))
            {
                comboBoxCompresion.Enabled = false;
                comboBoxCompresion.SelectedIndex = comboBoxCompresion.Items.IndexOf("Mpeg2");
                comboBoxContainer.Enabled = false;
                comboBoxContainer.SelectedIndex = comboBoxContainer.Items.IndexOf("VOB");
                
                return;
            }

            // Vybrano videoCD
            if ("CD".Equals(comboBoxMedia.Items[comboBoxMedia.SelectedIndex]) && "CD-Video".Equals(comboBoxQuality.Items[comboBoxQuality.SelectedIndex]))
            {
                comboBoxCompresion.Enabled = false;
                comboBoxCompresion.SelectedIndex = comboBoxCompresion.Items.IndexOf("Mpeg");
                comboBoxContainer.Enabled = false;
                comboBoxContainer.SelectedIndex = comboBoxContainer.Items.IndexOf("Jiný");

                return;
            }

            // HD DVD
            if ("HD-DVD".Equals(comboBoxMedia.Items[comboBoxMedia.SelectedIndex]) && "HDDVD-Video".Equals(comboBoxQuality.Items[comboBoxQuality.SelectedIndex]))
            {
                comboBoxCompresion.Enabled = false;
                comboBoxCompresion.SelectedIndex = comboBoxCompresion.Items.IndexOf("Jiná");
                comboBoxContainer.Enabled = false;
                comboBoxContainer.SelectedIndex = comboBoxContainer.Items.IndexOf("Jiný");

                return;
            }

            // BD
            if ("Blue-ray".Equals(comboBoxMedia.Items[comboBoxMedia.SelectedIndex]) && "BD-Video".Equals(comboBoxQuality.Items[comboBoxQuality.SelectedIndex]))
            {
                comboBoxCompresion.Enabled = false;
                comboBoxCompresion.SelectedIndex = comboBoxCompresion.Items.IndexOf("H.264");
                comboBoxContainer.Enabled = false;
                comboBoxContainer.SelectedIndex = comboBoxContainer.Items.IndexOf("Jiný");

                return;
            }

            // Videokazeta
            if ("VHS".Equals(comboBoxMedia.Items[comboBoxMedia.SelectedIndex]))
            {
                comboBoxQuality.Enabled = false;
                comboBoxQuality.SelectedIndex = comboBoxQuality.Items.IndexOf("Jiná");
                comboBoxCompresion.Enabled = false;
                comboBoxCompresion.SelectedIndex = comboBoxCompresion.Items.IndexOf("Jiná");
                comboBoxContainer.Enabled = false;
                comboBoxContainer.SelectedIndex = comboBoxContainer.Items.IndexOf("Jiný");

                return;
            }


            comboBoxQuality.Enabled = true;
            comboBoxCompresion.Enabled = true;
            comboBoxContainer.Enabled = true;
        }

        #endregion

        #region ovladani menu

        /// <summary>
        /// Otevreni ulozeneho souboru
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void otevřítToolStripMenuItem_Click(object sender, EventArgs e)
        {
            handleUnsaved();

            DialogResult result = openFileDialog1.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                Boolean upgraded = false;
                loader = new Loader();
                try
                {
                    filmList = loader.load(openFileDialog1.FileName, out upgraded);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message);
                    return;
                }

                saver = new Saver(openFileDialog1.FileName);
                saved = !upgraded;
                Text = upgraded ? String.Format(Properties.Messages.form_main_text, openFileDialog1.FileName + "*") : String.Format(Properties.Messages.form_main_text, openFileDialog1.FileName);                

                updateFilmList();
            }
        }

        /// <summary>
        /// Ulozeni seznamu do souboru
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uložitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (filmList == null || filmList.Count <= 0) return;

            if (saver != null)
            {
                try
                {
                    String version = Tools.AssemblyVersion;
                    if (version.Contains("beta")) version = version.Substring(0, 3);
                    saver.save(version, filmList);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                saved = true;
                Text = String.Format(Properties.Messages.form_main_text, saver.FileName);
            }
            else
            {
                uložitJakoToolStripMenuItem_Click(sender, e);
            }
        }

        /// <summary>
        /// Ulozeni seznamu do noveho souboru
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uložitJakoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (filmList == null || filmList.Count <= 0) return;

            DialogResult result = saveFileDialog1.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                Saver oldSaver = saver;
                try
                {
                    saver = new Saver(saveFileDialog1.FileName);
                    String version = Tools.AssemblyVersion;
                    if (version.Contains("beta")) version = version.Substring(0, 3);
                    saver.save(version, filmList);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    saver = oldSaver;
                    return;
                }               
                
                saved = true;
                Text = String.Format(Properties.Messages.form_main_text, saver.FileName);
            }
        }

        /// <summary>
        /// Zobrazeni about dialogu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AboutForm().Show(this);            
        }

        /// <summary>
        /// Ukonceni programu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void konecToolStripMenuItem_Click(object sender, EventArgs e)
        {
            handleUnsaved();
            Close();
        }

        private void internetovéStránkyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tools.openPageInBrowser("http://code.google.com/p/dvdfilmoteka/");
        }

        private void uživatelskáPříručkaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tools.openPageInBrowser("http://code.google.com/p/dvdfilmoteka/wiki/UserGuide");
        }

        private void diskuzníFórumToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tools.openPageInBrowser("http://groups.google.com/group/dvdfilmoteka");
        }

        private void hlášeníChybAPřipomínkyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tools.openPageInBrowser("http://code.google.com/p/dvdfilmoteka/issues/entry");
        }

        private void vyhledatDuplicitníNázvyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<MovieDataStore12> duplicity = new List<MovieDataStore12>();

            for (int i = 0; i < filmList.Count; i++) //Projet vsechny
            {
                MovieDataStore12 item = filmList[i];

                for (int j = i + 1; j < filmList.Count; j++) // Projet zbyvajici
                {
                    if (item.czechName.Equals(filmList[j].czechName)) //Je stejny nazev, tak ulozit do seznamu
                    {
                        duplicity.Add(item);
                        break;
                    }
                }
            }

            if (duplicity.Count == 0) //Nejsou zadne duplicity
            {
                MessageBox.Show(Properties.Messages.messages_noduplicity_msg, Properties.Messages.form_findduplicity_text, MessageBoxButtons.OK);
            }
            else
            {
                FindDuplicity duplicityForm = new FindDuplicity(duplicity);
                duplicityForm.ShowDialog(this);
            }
        }

        private void šablonaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateTemplate templateDialog = new CreateTemplate();
            templateDialog.ShowDialog(this);
        }

        /// <summary>
        /// Pridani vice filmu najednou
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void víceFilmůToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MovieDataStore12 defaultDataStore = new MovieDataStore12();
            defaultDataStore.czechName = "";
            defaultDataStore.originalName = "";
            defaultDataStore.link = "";
            defaultDataStore.movieNotes = "";
            defaultDataStore.resolution = textBoxResolution.Text;
            defaultDataStore.size = (String)comboBoxSize.Items[comboBoxSize.SelectedIndex];
            defaultDataStore.mediumNotes = "";
            defaultDataStore.csfdRating = "";

            defaultDataStore.myRating = (String)comboBoxMyRating.SelectedItem;
            defaultDataStore.mainGenre = (comboBoxMainGenre.SelectedItem as GenreItem).Name;
            defaultDataStore.otherGenre.Clear();
            foreach (GenreItem item in checkedListBoxOtherGenres.CheckedItems)
            {
                defaultDataStore.otherGenre.Add(item.ID);
            }
            defaultDataStore.medium = (String)comboBoxMedia.SelectedItem;
            defaultDataStore.quality = (String)comboBoxQuality.SelectedItem;
            defaultDataStore.compression = (String)comboBoxCompresion.SelectedItem;
            defaultDataStore.container = (String)comboBoxContainer.SelectedItem;
            defaultDataStore.language = (String)comboBoxLanguage.SelectedItem;
            defaultDataStore.channelCount = (String)comboBoxChanelCount.SelectedItem;

            new ImportForm(this, defaultDataStore).ShowDialog(this);            
        }

        /// <summary>
        /// Export do externiho souboru
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exportovatToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new ExporterForm(filmList).ShowDialog(this);
        }

        /// <summary>
        /// Novy seznam filmu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void newSeznamFilmůToolStripMenuItem_Click(object sender, EventArgs e)
        {
            handleUnsaved();

            treeView1.Nodes.Clear();
            filmList.Clear();

            textBoxCzechName.Text = "";
            textBoxOriginalName.Text = "";
            textBoxLinks.Text = "";
            textBoxMovieNotes.Text = "";
            textBoxResolution.Text = "";
            textBoxMediaNotes.Text = "";
            textBoxCSFDRating.Text = "";
            pictureBoxMoviePicture.Image = null;

            saved = true;
            Text = String.Format(Properties.Messages.form_main_text, Properties.Messages.messages_notsaved);            
        }

        private void vyhledatVšechnyNaCSFDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (filmList.Count <= 0) return;

            pozice = -1;
            if (treeView1.SelectedNode != null && (treeView1.SelectedNode.Tag is MovieDataStore12)) pozice = filmList.IndexOf((MovieDataStore12)treeView1.SelectedNode.Tag);

            FindAllForm form = new FindAllForm(filmList, EServerDatabases.CSFD, this, true);
            form.ShowDialog(this);
        }

        private void vyhledatVšechnyNaIMDBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (filmList.Count <= 0) return;

            pozice = -1;
            if (treeView1.SelectedNode != null && (treeView1.SelectedNode.Tag is MovieDataStore12)) pozice = filmList.IndexOf((MovieDataStore12)treeView1.SelectedNode.Tag);

            FindAllForm form = new FindAllForm(filmList, EServerDatabases.IMDB, this, true);
            form.ShowDialog(this);
        }

        private void vyhledatDosudNevyhledanéNaCSFDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (filmList.Count <= 0) return;

            pozice = -1;
            if (treeView1.SelectedNode != null && (treeView1.SelectedNode.Tag is MovieDataStore12)) pozice = filmList.IndexOf((MovieDataStore12)treeView1.SelectedNode.Tag);

            FindAllForm form = new FindAllForm(filmList, EServerDatabases.CSFD, this, false);
            form.ShowDialog(this);
        } 

        public void vyhledatVšechnyComplete(List<MovieDataStore12> updatedFilmList, List<FindAllReport> report, Boolean updated)
        {
            if (!updated) return;

            // Zobrazi vysledky hledani
            if (SettingsManager.Instance.Data.ViewResults)
            {
                FindAllReportForm reportForm = new FindAllReportForm(report);
                reportForm.Show(this);
            }

            filmList = updatedFilmList;

            if (pozice >= 0)
            {
                treeView1.SelectedNode.Tag = filmList[pozice];
            }

            saved = false;
            if (saver != null)
            {
                Text = String.Format(Properties.Messages.form_main_text, saver.FileName + "*");                
            }

            updateFilmList();
        }

        private void umístitLinkyNaCSFDNaPrvníMístoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (MovieDataStore12 item in filmList)
            {
                if (item.link.ToLower().Contains("csfd")) //Pokud je v zaznamu csfd
                {
                    String newLink = "";
                    String[] linky = item.link.Split(' '); // Rozdeli linky podle mezer
                    foreach (String item2 in linky)
                    {
                        if (item2.ToLower().Contains("csfd"))
                        {
                            newLink = item2 + newLink + " "; // Prida linku na prvni misto
                        }
                        else
                        {
                            newLink = newLink + item2 + " "; // Prida linku na posledni misto
                        }
                    }

                    newLink = newLink.Trim();
                    item.link = newLink;
                }
            }
        }

        private void umístitLinkyNaIMDBNaPrvníMístoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (MovieDataStore12 item in filmList)
            {
                if (item.link.ToLower().Contains("imdb")) //Pokud je v zaznamu csfd
                {
                    String newLink = "";
                    String[] linky = item.link.Split(' '); // Rozdeli linky podle mezer
                    foreach (String item2 in linky)
                    {
                        if (item2.ToLower().Contains("imdb"))
                        {
                            newLink = item2 + newLink + " "; // Prida linku na prvni misto
                        }
                        else
                        {
                            newLink = newLink + item2 + " "; // Prida linku na posledni misto
                        }
                    }

                    newLink = newLink.Trim();
                    item.link = newLink;
                }
            }
        }

        private void nastaveníToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Settings().ShowDialog(this);
        }

        private void vyhledatNovéVerzeNaInternetuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ApplicationUpdater.Instance.checkNewVersionAsync(true);
        }

        #endregion

        #region ovladani treeView
        /// <summary>
        /// Pridani filmu do seznamu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void přidatFilmToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MediaTemplate template = TemplateManager.Instance.GetTemplateByName("default");
            if ((sender is ToolStripMenuItem) && ((sender as ToolStripMenuItem).Tag is String))
            {
                String templateName = (String)(sender as ToolStripMenuItem).Tag;

                if (!String.IsNullOrEmpty(templateName))
                {
                    template = TemplateManager.Instance.GetTemplateByName(templateName);
                }
            }
            
            MovieDataStore12 newDataStore = new MovieDataStore12();

            newDataStore.size = template.size;
            newDataStore.fileName = "";
            newDataStore.movieNotes = "";
            newDataStore.csfdRating = "";
            newDataStore.myRating = "Nevyplněno";
            newDataStore.compression = template.compression;
            newDataStore.container = template.container;
            newDataStore.quality = template.quality;
            newDataStore.link = "";
            newDataStore.medium = template.medium;
            newDataStore.mediumNotes = "";
            newDataStore.resolution = template.resolution;
            newDataStore.mainGenre = Tools.NoGenre.Name;            
            newDataStore.otherGenre.Clear();            
            newDataStore.language = template.language;
            newDataStore.channelCount = template.channelCount;
            newDataStore.czechName = Properties.Messages.messages_noname_czech;
            newDataStore.originalName = Properties.Messages.messages_noname_original;
            newDataStore.timeOfAddtion = DateTime.Now;
            newDataStore.pictureLink = "";
            newDataStore.pictureData = null;

            filmList.Add(newDataStore);

            updateFilmList();

            // Vybere prave pridany film
            setSelectedNode(treeView1.Nodes, newDataStore);

            saved = false;
            if (saver != null)
            {
                Text = String.Format(Properties.Messages.form_main_text, saver.FileName + "*");
            }
        }        

        /// <summary>
        /// Vymazani filmu ze seznamu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void vymazatFilmToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!(treeView1.SelectedNode.Tag is MovieDataStore12)) return;

            filmList.Remove((MovieDataStore12)treeView1.SelectedNode.Tag);

            TreeNode parentNode = treeView1.SelectedNode.Parent;
            treeView1.SelectedNode.Remove();

            if (parentNode != null && parentNode.Nodes.Count <= 0) parentNode.Remove();

            saved = false;
            if (saver != null)
            {
                Text = String.Format(Properties.Messages.form_main_text, saver.FileName + "*");
            }

            filteredMovies--;
            updateMovieCountVisual();
        }

        private void treeView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);
            }
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            contextMenuStrip.Items[0].Enabled = true;
            ((ToolStripMenuItem)contextMenuStrip.Items[0]).DropDownItems.Clear();

            // Pridat sablony
            foreach (String item in TemplateManager.Instance.AvailableTemplateNames)
            {
                ToolStripMenuItem templateItem = new ToolStripMenuItem();
                templateItem.Text = item;
                templateItem.Tag = item;
                templateItem.Click += new EventHandler(přidatFilmToolStripMenuItem_Click);
                if ("default".Equals(item))
                {
                    templateItem.ShortcutKeys = Keys.Insert;
                    templateItem.ShowShortcutKeys = false;
                }

                ((ToolStripMenuItem)contextMenuStrip.Items[0]).DropDownItems.Add(templateItem);
            }


            if (treeView1.SelectedNode == null || treeView1.SelectedNode.Tag == null)
            {
                contextMenuStrip.Items[1].Enabled = false;
                contextMenuStrip.Items[2].Enabled = false;
                contextMenuStrip.Items[3].Enabled = false;
                contextMenuStrip.Items[4].Enabled = false;
            }
            else
            {
                contextMenuStrip.Items[1].Enabled = true;
                contextMenuStrip.Items[2].Enabled = true;
                contextMenuStrip.Items[3].Enabled = true;
                contextMenuStrip.Items[4].Enabled = true;
            }

            if (treeView1.Nodes.Count <= 0 || treeView1.Nodes[0].Nodes == null)
            {
                contextMenuStrip.Items[5].Enabled = false;
                contextMenuStrip.Items[6].Enabled = false;
            }
            else
            {
                contextMenuStrip.Items[5].Enabled = true;
                contextMenuStrip.Items[6].Enabled = true;
            }
        }

        private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (treeView1.SelectedNode == null) return;

            treeView1.SelectedNode.ForeColor = Color.Black; // Vrati se nodu puvodni barva
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            List<GenreItem> zanrList = Tools.getZanrNodeList();

            if (treeView1.SelectedNode == null || !(treeView1.SelectedNode.Tag is MovieDataStore12))
            {
                transaction = true;

                textBoxCzechName.Text = "";
                textBoxOriginalName.Text = "";
                textBoxLinks.Text = "";
                textBoxMovieNotes.Text = "";
                textBoxResolution.Text = "";
                comboBoxChanelCount.SelectedIndex = 0;
                textBoxMediaNotes.Text = "";
                textBoxCSFDRating.Text = "";
                textBoxIMDBRating.Text = "";

                comboBoxMainGenre.Items.Clear();
                comboBoxMainGenre.Items.AddRange(zanrList.ToArray());
                try
                {
                    if (comboBoxMainGenre.Items.Count > 0) comboBoxMainGenre.SelectedItem = Tools.NoGenre;
                } catch
                {
                    comboBoxMainGenre.SelectedIndex = 0;
                }

                comboBoxMyRating.SelectedIndex = 0;
                comboBoxMedia.SelectedIndex = 0;
                comboBoxQuality.SelectedIndex = 0;
                comboBoxCompresion.SelectedIndex = 0;
                comboBoxContainer.SelectedIndex = 0;
                comboBoxLanguage.SelectedIndex = 0;
                comboBoxChanelCount.SelectedIndex = 0;
                comboBoxSize.SelectedIndex = 0;
                                
                checkedListBoxOtherGenres.BeginUpdate();
                for (int index2 = 0; index2 < checkedListBoxOtherGenres.Items.Count; index2++)
                {
                    checkedListBoxOtherGenres.SetItemCheckState(index2, CheckState.Unchecked);
                }
                checkedListBoxOtherGenres.EndUpdate();

                pictureBoxMoviePicture.Image = pictureBoxMoviePicture.InitialImage;

                transaction = false;

                return;
            }

            MovieDataStore12 store = (MovieDataStore12) treeView1.SelectedNode.Tag;
            if (store == null) return;

            treeView1.SelectedNode.ForeColor = Color.Red; // Vybrany node se oznaci cervene

            transaction = true;

            textBoxCzechName.Text = store.czechName;
            textBoxOriginalName.Text = store.originalName;
            textBoxLinks.Text = store.link;
            textBoxMovieNotes.Text = store.movieNotes;
            textBoxResolution.Text = store.resolution;
            textBoxMediaNotes.Text = store.mediumNotes;
            textBoxCSFDRating.Text = store.csfdRating;
            textBoxIMDBRating.Text = store.imdbRating;

            comboBoxMyRating.SelectedIndex = comboBoxMyRating.Items.IndexOf(store.myRating) >= 0 ? comboBoxMyRating.Items.IndexOf(store.myRating) : 0;            
            comboBoxMedia.SelectedIndex = comboBoxMedia.Items.IndexOf(store.medium) >= 0 ? comboBoxMedia.Items.IndexOf(store.medium) : 0;
            comboBoxQuality.SelectedIndex = comboBoxQuality.Items.IndexOf(store.quality) >= 0 ? comboBoxQuality.Items.IndexOf(store.quality) : 0;
            comboBoxCompresion.SelectedIndex = comboBoxCompresion.Items.IndexOf(store.compression) >= 0 ? comboBoxCompresion.Items.IndexOf(store.compression) : 0;
            comboBoxContainer.SelectedIndex = comboBoxContainer.Items.IndexOf(store.container) >= 0 ? comboBoxContainer.Items.IndexOf(store.container) : 0;
            comboBoxSize.SelectedIndex = comboBoxSize.Items.IndexOf(store.size) >= 0 ? comboBoxSize.Items.IndexOf(store.size) : 0;
            comboBoxLanguage.SelectedIndex = comboBoxLanguage.Items.IndexOf(store.language) >= 0 ? comboBoxLanguage.Items.IndexOf(store.language) : 0;
            comboBoxChanelCount.SelectedIndex = comboBoxChanelCount.Items.IndexOf(store.channelCount) >= 0 ? comboBoxChanelCount.Items.IndexOf(store.channelCount) : 0;

            comboBoxMainGenre.Items.Clear();
            checkedListBoxOtherGenres.BeginUpdate();
            for (int index2 = 0; index2 < checkedListBoxOtherGenres.Items.Count; index2++)
            {
                GenreItem genreItem = checkedListBoxOtherGenres.Items[index2] as GenreItem;
                if (genreItem != null && store.otherGenre.Contains(genreItem.ID))
                {
                    checkedListBoxOtherGenres.SetItemCheckState(index2, CheckState.Checked);
                    comboBoxMainGenre.Items.Add(genreItem);
                }
                else
                {
                    checkedListBoxOtherGenres.SetItemCheckState(index2, CheckState.Unchecked);
                }
            }
            checkedListBoxOtherGenres.EndUpdate();

            if (comboBoxMainGenre.Items.Count <= 0) comboBoxMainGenre.Items.Add(Tools.NoGenre);
            comboBoxMainGenre.SelectedIndex = comboBoxMainGenre.Items.IndexOf(Tools.GetGenreByName(store.mainGenre)) >= 0 ? comboBoxMainGenre.Items.IndexOf(Tools.GetGenreByName(store.mainGenre)) : 0;

            listBoxActors.BeginUpdate();
            listBoxActors.Items.Clear();
            foreach (var item in store.actors.Keys)
            {
                listBoxActors.Items.Add(item);
            }
            listBoxActors.EndUpdate();

            labelCountry.Text = String.Format(Properties.Messages.form_main_labelCountry, store.country);
            labelLength.Text = String.Format(Properties.Messages.form_main_labelLength, store.length);
            labelYear.Text = String.Format(Properties.Messages.form_main_labelYear, store.year);
            textBoxObsah.Text = store.recenze;
            linkLabelDirector.Text = store.directorName;
            linkLabelDirector.Enabled = !String.IsNullOrEmpty(store.directorLink);            

            // Obrazek filmu
            try
            {
                if (!String.IsNullOrEmpty(store.pictureData))
                {
                    byte[] data = Convert.FromBase64String(store.pictureData); // Ulozit v Base64

                    MemoryStream imageStream = new MemoryStream(data);
                    imageStream.Position = 0;

                    pictureBoxMoviePicture.Image = new Bitmap(imageStream); // Zobrazit                    
                }
                else if (!String.IsNullOrEmpty(store.pictureLink))
                {
                    pictureBoxMoviePicture.Image = Properties.Resources.loading;
                    pictureBoxMoviePicture.LoadAsync(store.pictureLink);
                }
                else
                {
                    pictureBoxMoviePicture.Image = pictureBoxMoviePicture.InitialImage;
                }
            }
            catch
            {
                pictureBoxMoviePicture.Image = pictureBoxMoviePicture.ErrorImage;
            }

            transaction = false;
        }

        /// <summary>
        /// Nacist udaje z CSFD
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void načístToolStripMenuItem_Click(object sender, EventArgs e)
        {
            buttonVyhledatNaCSFD_Click(sender, e);
        }

        /// <summary>
        /// Nacist udaje z IMDB
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void načístÚdajeOFilmuIMDBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            buttonVyhledatNaIMDB_Click(sender, e);
        } 

        /// <summary>
        /// Expanduje vsechny
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rozbalitVšechnyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeView1.ExpandAll();
        }

        /// <summary>
        /// Zabali vsechny
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sbalitVšechnyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeView1.CollapseAll();
        }

        #endregion

        #region Tlacitka
        /// <summary>
        /// Vyhledat film na CSFD a zapsat udaje do plozek
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonVyhledatNaCSFD_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null || !(treeView1.SelectedNode.Tag is MovieDataStore12)) return;
            MovieDataStore12 oldFilmData = (MovieDataStore12)treeView1.SelectedNode.Tag;
            if (oldFilmData == null) return;

            String filmName = oldFilmData.czechName;
            if (String.IsNullOrEmpty(filmName))
            {
                filmName = oldFilmData.originalName;
            }

            if (String.IsNullOrEmpty(filmName)) return;

            Cursor.Current = Cursors.WaitCursor;

            IServerDatabase serverDatabase = ServerDatabaseFactory.getInstance(EServerDatabases.CSFD);
            MovieDataStore12 filmData = serverDatabase.getFilmData(filmName);

            if (filmData != null)
            {
                // Zachovat puvodni data
                filmData.imdbRating = oldFilmData.imdbRating;

                // Zobrazit a ulozit
                fillForm(filmData);
                comboBoxSorting_SelectedIndexChanged(null, null);
                Cursor.Current = Cursors.Arrow;                
            }
            else
            {
                Cursor.Current = Cursors.Arrow;
                MessageBox.Show(Properties.Messages.messages_wrongname);
            }
        }

        /// <summary>
        /// Vyhledat na IMDB
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonVyhledatNaIMDB_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null || !(treeView1.SelectedNode.Tag is MovieDataStore12)) return;
            MovieDataStore12 oldFilmData = (MovieDataStore12)treeView1.SelectedNode.Tag;
            if (oldFilmData == null) return;

            String filmName = oldFilmData.originalName;
            if (String.IsNullOrEmpty(filmName))
            {
                filmName = oldFilmData.czechName;
            }

            if (String.IsNullOrEmpty(filmName)) return;

            Cursor.Current = Cursors.WaitCursor;

            IServerDatabase serverDatabase = ServerDatabaseFactory.getInstance(EServerDatabases.IMDB);
            MovieDataStore12 filmData = serverDatabase.getFilmData(filmName);

            if (filmData != null)
            {
                // Zapsat vyhledana data
                oldFilmData.imdbRating = filmData.imdbRating;
                oldFilmData.link = filmData.link;

                // Zobrazit a ulozit
                fillForm(oldFilmData);
                comboBoxSorting_SelectedIndexChanged(null, null);
                Cursor.Current = Cursors.Arrow;               
            }
            else
            {
                Cursor.Current = Cursors.Arrow;
                MessageBox.Show(Properties.Messages.messages_wrongname);
            }
        } 

        /// <summary>
        /// Tlacitko PREJIT
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonPrejit_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null || !(treeView1.SelectedNode.Tag is MovieDataStore12)) return;
            MovieDataStore12 oldFilmData = (MovieDataStore12)treeView1.SelectedNode.Tag;
            if (oldFilmData == null) return;
            if (String.IsNullOrEmpty(oldFilmData.link)) return;

            String[] linkList = oldFilmData.link.Split(' ');
            // Otevrit v prohlizeci
            Tools.openPageInBrowser(linkList[0]);
        }

        /// <summary>
        /// Nacist z adres
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonNacistZAdres_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null || !(treeView1.SelectedNode.Tag is MovieDataStore12)) return;
            MovieDataStore12 oldFilmData = (MovieDataStore12)treeView1.SelectedNode.Tag;
            if (oldFilmData == null) return;
            if (String.IsNullOrEmpty(oldFilmData.link)) return;

            Cursor.Current = Cursors.WaitCursor;

            String[] linkList = oldFilmData.link.Split(' ');
            foreach (String link in linkList) // Projet vsechny zadane adresy
            {
                EServerDatabases eServerDatabase;
                if (link.ToLower().Contains("imdb"))
                {
                    eServerDatabase = EServerDatabases.IMDB;
                }
                else if (link.ToLower().Contains("csfd"))
                {
                    eServerDatabase = EServerDatabases.CSFD;
                }
                else
                {
                    Cursor.Current = Cursors.Arrow;
                    return;
                }
                IServerDatabase serverDatabase = ServerDatabaseFactory.getInstance(eServerDatabase);
                MovieDataStore12 filmData = serverDatabase.getFilmDataFromLink(link);

                if (filmData != null)
                {
                    if (eServerDatabase == EServerDatabases.IMDB)
                    {
                        // Zachovat ulozena data
                        oldFilmData.imdbRating = filmData.imdbRating;
                        oldFilmData.link = filmData.link;
                        fillForm(oldFilmData);
                    }
                    else
                    {
                        // Zapsat vyhledana data
                        filmData.imdbRating = oldFilmData.imdbRating;
                        fillForm(filmData);
                    }
                    comboBoxSorting_SelectedIndexChanged(null, null);
                    
                    Cursor.Current = Cursors.Arrow;
                }
                else
                {
                    Cursor.Current = Cursors.Arrow;
                    MessageBox.Show(String.Format(Properties.Messages.messages_wronglink, link));
                }
            }
        }

        

        #endregion

        /// <summary>
        /// Otevre rezisera v browseru
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabelDerector_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
        {
            if (treeView1.SelectedNode == null || !(treeView1.SelectedNode.Tag is MovieDataStore12)) return;
            MovieDataStore12 filmData = (MovieDataStore12)treeView1.SelectedNode.Tag;

            linkLabelDirector.LinkVisited = true;
            if (!String.IsNullOrEmpty(filmData.directorLink)) Tools.openPageInBrowser(filmData.directorLink);
        }

        /// <summary>
        /// Vyplni formular podle zadaneho MovieDataStoru
        /// </summary>
        /// <param name="filmData"></param>
        private void fillForm(MovieDataStore12 filmData)
        {
            transaction = true;
            
            if (!SettingsManager.Instance.Data.DontChangeGenres && filmData.otherGenre != null && filmData.otherGenre.Count > 0)
            {
                comboBoxMainGenre.Items.Clear();
                checkedListBoxOtherGenres.BeginUpdate();
                for (int index2 = 0; index2 < checkedListBoxOtherGenres.Items.Count; index2++)
                {
                    GenreItem genreItem = checkedListBoxOtherGenres.Items[index2] as GenreItem;
                    if (genreItem != null && filmData.otherGenre.Contains(genreItem.ID))
                    {
                        checkedListBoxOtherGenres.SetItemCheckState(index2, CheckState.Checked);
                        comboBoxMainGenre.Items.Add(genreItem);
                    }
                    else
                    {
                        checkedListBoxOtherGenres.SetItemCheckState(index2, CheckState.Unchecked);
                    }
                }
                checkedListBoxOtherGenres.EndUpdate();

                if (comboBoxMainGenre.Items.Count <= 0) comboBoxMainGenre.Items.Add(Tools.NoGenre);
                comboBoxMainGenre.SelectedIndex = comboBoxMainGenre.Items.IndexOf(Tools.GetGenreByName(filmData.mainGenre)) >= 0 ? comboBoxMainGenre.Items.IndexOf(Tools.GetGenreByName(filmData.mainGenre)) : 0;
            }

            if ((!SettingsManager.Instance.Data.DontChangeNames || String.IsNullOrEmpty(textBoxCzechName.Text)) && !String.IsNullOrEmpty(filmData.czechName)) textBoxCzechName.Text = filmData.czechName;
            if ((!SettingsManager.Instance.Data.DontChangeNames || String.IsNullOrEmpty(textBoxOriginalName.Text)) && !String.IsNullOrEmpty(filmData.originalName)) textBoxOriginalName.Text = filmData.originalName;
            if (!String.IsNullOrEmpty(filmData.csfdRating)) textBoxCSFDRating.Text = filmData.csfdRating;
            if (!SettingsManager.Instance.Data.DontChangeGenres && !String.IsNullOrEmpty(filmData.mainGenre))
            {
                try
                {
                    if (comboBoxMainGenre.Items.Count <= 0)
                    {
                        filmData.mainGenre = Tools.NoGenre.Name;
                        comboBoxMainGenre.Items.Add(Tools.NoGenre);
                    }

                    comboBoxMainGenre.SelectedItem = Tools.GetGenreByName(filmData.mainGenre);
                }
                catch { }
            }
            if (!String.IsNullOrEmpty(filmData.imdbRating)) textBoxIMDBRating.Text = filmData.imdbRating;
            if (!String.IsNullOrEmpty(filmData.link)) textBoxLinks.Text = addLink(textBoxLinks.Text, filmData.link);

            if (filmData.actors != null)
            {
                listBoxActors.BeginUpdate();
                listBoxActors.Items.Clear();
                foreach (var item in filmData.actors.Keys)
                {
                    listBoxActors.Items.Add(item);
                }
                listBoxActors.EndUpdate();
            }
            if (!String.IsNullOrEmpty(filmData.country)) labelCountry.Text = String.Format(Properties.Messages.form_main_labelCountry, filmData.country);
            if (!String.IsNullOrEmpty(filmData.length)) labelLength.Text = String.Format(Properties.Messages.form_main_labelLength, filmData.length);
            if (!String.IsNullOrEmpty(filmData.recenze)) textBoxObsah.Text = filmData.recenze;
            if (!String.IsNullOrEmpty(filmData.year)) labelYear.Text = String.Format(Properties.Messages.form_main_labelYear, filmData.year);
            if (!String.IsNullOrEmpty(filmData.directorName))
            {
                linkLabelDirector.Text = filmData.directorName;
                linkLabelDirector.Enabled = !String.IsNullOrEmpty(filmData.directorLink);                
            }

            if (treeView1.SelectedNode != null && (treeView1.SelectedNode.Tag is MovieDataStore12))
            {
                MovieDataStore12 selfilmData = (MovieDataStore12)treeView1.SelectedNode.Tag;

                selfilmData.actors = filmData.actors;
                selfilmData.country = filmData.country;
                selfilmData.csfdRating = filmData.csfdRating;
                selfilmData.directorLink = filmData.directorLink;
                selfilmData.directorName = filmData.directorName;
                selfilmData.imdbRating = filmData.imdbRating;
                selfilmData.length = filmData.length;
                selfilmData.recenze = filmData.recenze;
                selfilmData.year = filmData.year;
            }

            transaction = false;

            moviePictureChanged(filmData.pictureLink);
            somethingChanged(this, new EventArgs());            
        }

        /// <summary>
        /// Prida link do seznamu
        /// </summary>
        /// <param name="link"></param>
        /// <param name="addLink"></param>
        public String addLink(String link, String addLink)
        {
            if (string.IsNullOrEmpty(addLink)) return null;
            if (string.IsNullOrEmpty(link))
            {
                return addLink;
            }

            String serverSign = "";
            if (addLink.ToLower().Contains("csfd")) serverSign = "csfd";
            if (addLink.ToLower().Contains("imdb")) serverSign = "imdb";

            Boolean added = false;
            String returnString = "";
            String[] linkList = link.Split(' ');
            foreach (String item in linkList)
            {
                if (!item.ToLower().Contains(serverSign))
                {
                    returnString += " " + item;
                }
                else
                {
                    returnString += " " + addLink;
                    added = true;
                }
            }

            if (!added) returnString += " " + addLink;

            return returnString.Trim();
        }

        /// <summary>
        /// Osetri pripad, ze neni ulozeno
        /// </summary>
        private void handleUnsaved()
        {
            if (saved) return;

            String message = Properties.Messages.messages_unsaved_msg;
            String caption = Properties.Messages.messages_unsaved_title;
            const MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            DialogResult result = MessageBox.Show(this, message, caption, buttons, MessageBoxIcon.Exclamation);

            if (result == System.Windows.Forms.DialogResult.Yes)
            {
                uložitToolStripMenuItem_Click(null, null);
            }
        }

        /// <summary>
        /// Zmeni text s mnozstvim filmu ve filmotece
        /// </summary>
        private void updateMovieCountVisual()
        {
            labelMovieCount.Text = String.Format(Properties.Messages.form_main_labelMovieCount, filteredMovies, filmList.Count);            
        }

        /// <summary>
        /// Najde a nastavi node s filmem jako vybrany.
        /// </summary>
        /// <param name="where"></param>
        /// <param name="movie"></param>
        private void setSelectedNode(TreeNodeCollection where, MovieDataStore12 movie)
        {
            foreach (TreeNode item in where)
            {
                if (item.Nodes != null && item.Nodes.Count > 0) //Prejit o uroven niz
                {
                    setSelectedNode(item.Nodes, movie); // rekurze
                }

                if (item.Tag != null && movie.Equals(item.Tag))
                {
                    treeView1.SelectedNode = item;
                    return;
                }
            }
        }

        #region nova verze k dispozici

        /// <summary>
        /// Udalost zjisteni/stazeni nove verze
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnVersionGetEventHandler(object sender, ApplicationUpdateEventArgs e)
        {
            switch (e.eventType)
            {
                case ApplicationUpdateEventType.NEWVERSIONNOTAVAILABLE:
                    if ((e.userState is Boolean) && ((Boolean)e.userState))
                    {
                        String message = Properties.Messages.messages_noupdateavailable_msg;
                        String caption = Properties.Messages.messages_noupdateavailable_Text;
                        const MessageBoxButtons buttons = MessageBoxButtons.OK;
                        MessageBox.Show(this, message, caption, buttons, MessageBoxIcon.Information);
                    }
                    break;
                case ApplicationUpdateEventType.NEWBETAVERSIONAVAILABLE:
                    labelBeta.Visible = true;
                    break;
                case ApplicationUpdateEventType.NEWVERSIONAVAILABLE:
                    String message2 = String.Format(Properties.Messages.messages_updateavailable_msg, e.ActualVersion.ToString(3));
                    String caption2 = Properties.Messages.messages_updateavailable_Text;
                    DialogResult result = MessageBox.Show(this, message2, caption2, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (result == DialogResult.Yes)
                    {
                        ApplicationUpdater.Instance.downloadNewVersionAsync(this, e.ActualVersion, new DownloadProgress());
                    }
                    break;
                case ApplicationUpdateEventType.NEWVERSIONDOWNLOADED:
                    if (e.userState is String) newVersionDownloaded((String)e.userState);
                    break;
            }
        }

        /// <summary>
        /// Zavola se kdyz je nova verze stazena
        /// </summary>
        /// <param name="filePath"></param>
        private void newVersionDownloaded(String filePath)
        {
            String message = Properties.Messages.messages_newversiondownloaded_msg;
            String caption = Properties.Messages.messages_newversiondownloaded_Text;
            const MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            DialogResult result = MessageBox.Show(this, message, caption, buttons, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                uložitToolStripMenuItem_Click(this, null);

                WindowState = FormWindowState.Minimized;
                System.Diagnostics.Process.Start(filePath);
            }
            else
            {
                String message2 = String.Format(Properties.Messages.messages_newversiondownloaded_notinstalled_msg, filePath);
                String caption2 = Properties.Messages.messages_newversiondownloaded_notinstalled_Text;
                const MessageBoxButtons buttons2 = MessageBoxButtons.OK;
                MessageBox.Show(this, message2, caption2, buttons2, MessageBoxIcon.Information);
            }
        }
        #endregion        

        /// <summary>
        /// Predavani fokusu, kvuli scrolovani, kdyz je kurzor nad
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBoxActors_MouseEnter(object sender, EventArgs e)
        {
            listBoxActors.Focus();
        }

        public override void Localize()
        {
            this.Text = Properties.Messages.form_main_text;
            labelCompressionType.Text = Properties.Messages.form_main_labelCompressionType;
            labelContainerType.Text = Properties.Messages.form_main_labelContainerType;
            labelFileSize.Text = Properties.Messages.form_main_labelFileSize;
            labelChannelCount.Text = Properties.Messages.form_main_labelChannelCount;
            labelMainLanguage.Text = Properties.Messages.form_main_labelMainLanguage;
            labelMediaType.Text = Properties.Messages.form_main_labelMediaType;
            labelQuality.Text = Properties.Messages.form_main_labelQuality;
            labelResolution.Text = Properties.Messages.form_main_labelResolution;
            labelBeta.Text = Properties.Messages.form_main_labelBeta;
            labelCSFDRating.Text = Properties.Messages.form_main_labelCSFDRating;
            labelCzechName.Text = Properties.Messages.form_main_labelCzechName;
            labelDirector.Text = Properties.Messages.form_main_labelDirector;
            labelFilter.Text = Properties.Messages.form_main_labelFilter;
            labelIMDBRating.Text = Properties.Messages.form_main_labelIMDBRating;
            labelLinks.Text = Properties.Messages.form_main_labelLinks;
            labelMainGenre.Text = Properties.Messages.form_main_labelMainGenre;
            updateMovieCountVisual();            
            labelOriginalName.Text = Properties.Messages.form_main_labelOriginalName;
            labelPersonalRating.Text = Properties.Messages.form_main_labelPersonalRating;
            groupBoxActors.Text = Properties.Messages.form_main_groupBoxActors;
            groupBoxFilmNotes.Text = Properties.Messages.form_main_groupBoxFilmNotes;
            groupBoxInfo.Text = Properties.Messages.form_main_groupBoxInfo;
            groupBoxMediumNotes.Text = Properties.Messages.form_main_groupBoxMediumNotes;
            groupBoxSorting.Text = Properties.Messages.form_main_groupBoxSorting;
            buttonCSFDSearch.Text = Properties.Messages.form_main_buttonCSFDSearch;
            buttonGoto.Text = Properties.Messages.form_main_buttonGoto;
            buttonIMDBSearch.Text = Properties.Messages.form_main_buttonIMDBSearch;
            buttonLoadFromLinks.Text = Properties.Messages.form_main_buttonLoadFromLinks;
            tabPageMediumData.Text = Properties.Messages.form_main_tabPageMediumData;
            tabPageMovieData.Text = Properties.Messages.form_main_tabPageMovieData;
            tabPageMovieDataMore.Text = Properties.Messages.form_main_tabPageMovieDataMore;

            menuAbout.Text = Properties.Messages.form_main_menu_menuAbout;
            menuActualizations.Text = Properties.Messages.form_main_menu_menuActualizations;
            menuCSFDFirst.Text = Properties.Messages.form_main_menu_menuCSFDFirst;
            menuEnd.Text = Properties.Messages.form_main_menu_menuEnd;
            menuExport.Text = Properties.Messages.form_main_menu_menuExport;
            menuFile.Text = Properties.Messages.form_main_menu_menuFile;
            menuFindDuplicities.Text = Properties.Messages.form_main_menu_menuFindDuplicities;
            menuForum.Text = Properties.Messages.form_main_menu_menuForum;
            menuHelp.Text = Properties.Messages.form_main_menu_menuHelp;
            menuIMDBFirst.Text = Properties.Messages.form_main_menu_menuIMDBFirst;
            menuImport.Text = Properties.Messages.form_main_menu_menuImport;
            menuModification.Text = Properties.Messages.form_main_menu_menuModification;
            menuNew.Text = Properties.Messages.form_main_menu_menuNew;
            menuNewFilmoteka.Text = Properties.Messages.form_main_menu_menuNewFilmoteka;
            menuOpen.Text = Properties.Messages.form_main_menu_menuOpen;
            menuPages.Text = Properties.Messages.form_main_menu_menuPages;
            menuReport.Text = Properties.Messages.form_main_menu_menuReport;
            menuSave.Text = Properties.Messages.form_main_menu_menuSave;
            menuSaveAs.Text = Properties.Messages.form_main_menu_menuSaveAs;
            menuSearchAllCSFD.Text = Properties.Messages.form_main_menu_menuSearchAllCSFD;
            menuSearchAllIMDB.Text = Properties.Messages.form_main_menu_menuSearchAllIMDB;
            menuSearchNewVersions.Text = Properties.Messages.form_main_menu_menuSearchNewVersions;
            menuSearchNotSearchedCSFD.Text = Properties.Messages.form_main_menu_menuSearchNotSearchedCSFD;
            menuSettings.Text = Properties.Messages.form_main_menu_menuSettings;
            menuTemplate.Text = Properties.Messages.form_main_menu_menuTemplate;
            menuTools.Text = Properties.Messages.form_main_menu_menuTools;
            menuUserGuide.Text = Properties.Messages.form_main_menu_menuUserGuide;

            contextMenuAdd.Text = Properties.Messages.form_main_menu_contextMenuAdd;
            contextMenuColapseAll.Text = Properties.Messages.form_main_menu_contextMenuColapseAll;
            contextMenuDelete.Text = Properties.Messages.form_main_menu_contextMenuDelete;
            contextMenuExpandAll.Text = Properties.Messages.form_main_menu_contextMenuExpandAll;
            contextMenuSearchCSFD.Text = Properties.Messages.form_main_menu_contextMenuSearchCSFD;
            contextMenuSearchIMDB.Text = Properties.Messages.form_main_menu_contextMenuSearchIMDB;

            openFileDialog1.Title = Properties.Messages.messages_opendialog_Text;
            openFileDialog1.Filter = Properties.Messages.messages_opendialog_Filter;

            saveFileDialog1.Title = Properties.Messages.messages_savedialog_Text;
            saveFileDialog1.Filter = Properties.Messages.messages_savedialog_Filter;

            comboBoxSorting.Items.Clear();
            foreach (ISorter item in SorterStrategy.GetAvailableSorters())
            {
                comboBoxSorting.Items.Add(new Tools.SorterItem(item.Name(), item.Category()));
            }

            if (treeView1.SelectedNode != null && treeView1.SelectedNode.Tag != null)
            {
                MovieDataStore12 SelectedMovie = treeView1.SelectedNode.Tag as MovieDataStore12;

                if (!String.IsNullOrEmpty(SelectedMovie.country)) labelCountry.Text = String.Format(Properties.Messages.form_main_labelCountry, SelectedMovie.country);
                if (!String.IsNullOrEmpty(SelectedMovie.length)) labelLength.Text = String.Format(Properties.Messages.form_main_labelLength, SelectedMovie.length);
                if (!String.IsNullOrEmpty(SelectedMovie.year)) labelYear.Text = String.Format(Properties.Messages.form_main_labelYear, SelectedMovie.year);
            }
        }
    }
}